//
//  UIViewController+SwizzleDismissMethod.m
//  live4iphone
//
//  Created by jiachunke on 14-10-20.
//  Copyright (c) 2014年 Tencent Inc. All rights reserved.
//

#import "UIViewController+SwizzleDismissMethod.h"
#import <objc/runtime.h>
#import "NSObjectEx.h"

@implementation UIViewController (SwizzleDismissMethod)

+ (void)switchDismissMethod
{
    // 3.8开始，可能因为系统升级修复的原因，也可能因为App的横竖屏控制逻辑调整，这里不再需要做这个兼容了，兼容了反而会有负面影响，比如键盘在锁旋转时无法控制方向，tencent:jiachunke(20150207)
    /*
    // add by tencent:jiachunke(20141020)
    id UIViewControllerClass = objc_getClass("UIViewController");
    [UIViewControllerClass swizzleMethod:@selector(dismissViewControllerAnimated:completion:) withMethod:@selector(QLDismissViewControllerAnimated:completion:)];
    [UIViewControllerClass swizzleMethod:@selector(dismissModalViewControllerAnimated:) withMethod:@selector(QLDismissModalViewControllerAnimated:)];
     */
}

- (void)QLDismissViewControllerAnimated:(BOOL)flag completion:(void (^)(void))completion
{
    @try {
        // 3.7.1开始，由于页面的旋转因播放器旋转重构而放开，不再使用QLUnrotatableNavigationController锁屏，模态切换时如果模态前后方向不一致，
        // 系统的处理不够完善，上一个方向会影响到下一个，需要做一些保护性质的措施，基本是在AppDelegate做全局的方向上保护，tencent:jiachunke(20141020)
        __block AppDelegate *weakRTVC = (AppDelegate*)[[UIApplication sharedApplication] delegate];
        weakRTVC.modalViewControllerIsDismissing = YES;
        
        // 调用本方法反向切换回原方法，tencent:jiachunke(20141020)
        [self QLDismissViewControllerAnimated:flag completion:^(void){
            if (completion) {
                completion();
            }
            weakRTVC.modalViewControllerIsDismissing = NO;
        }];
        
        // dismiss后可以直接重置回来，tencent:jiachunke(20141024)
        weakRTVC.modalViewControllerIsDismissing = NO;
    }
    @catch (NSException *exception) {
        QLLogS(@"dismiss view controller with block excption=%@", exception);
    }
}

- (void)QLDismissModalViewControllerAnimated:(BOOL)animated
{
    @try {
        // 3.7.1开始，由于页面的旋转因播放器旋转重构而放开，不再使用QLUnrotatableNavigationController锁屏，模态切换时如果模态前后方向不一致，
        // 系统的处理不够完善，上一个方向会影响到下一个，需要做一些保护性质的措施，基本是在AppDelegate做全局的方向上保护，tencent:jiachunke(20141020)
        __block AppDelegate *weakRTVC = (AppDelegate*)[[UIApplication sharedApplication] delegate];
        weakRTVC.modalViewControllerIsDismissing = YES;
        
        // 调用本方法反向切换回原方法，tencent:jiachunke(20141020)
        [self QLDismissModalViewControllerAnimated:animated];
        
        // dismiss后可以直接重置回来，tencent:jiachunke(20141024)
        weakRTVC.modalViewControllerIsDismissing = NO;
    }
    @catch (NSException *exception) {
        QLLogS(@"dismiss view controller excption=%@", exception);
    }
}

@end
